using EasyNetQ;
using MF.Bus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ProviderTests
{
    class Program
    {
        static IBus bus = RabbitHutch.CreateBus("host=139.159.240.197:5672;virtualHost=bmm_test;username=admin;password=sydj520.com");
        static void Main(string[] args)
        {
            //SemaphoreTest();
            //var msg = Console.ReadLine();

            Console.WriteLine("请输入线程数和每个线程消息数,格式  thread,msg ");
            int threadNum = 0;
            int mqNum = 0;
            publishMsg(threadNum, mqNum);

        }

        public static void SemaphoreTest()
        {
            var semaphore = new SemaphoreSlim(5);
            for (int i = 1; i <= 50; i++)
            {
                Thread.Sleep(100); // 排队上桥
                var index = i; // 定义index 避免出现闭包的问题
                Task.Run(() =>
                {
                    semaphore.Wait();
                    try
                    {
                        Console.WriteLine($"第{index}个人正在过桥。");
                        Thread.Sleep(5000); // 模拟过桥需要花费的时间
                    }
                    finally
                    {
                        Console.WriteLine($"第{index}个人已经过桥。");
                        semaphore.Release();
                    }
                });
            }
        }

        static void publishMsg(int threadNum,int mqNum)
        {
            var msg = Console.ReadLine();
            var data = msg.Split(',');
            int.TryParse(data[0], out threadNum);
            int.TryParse(data[1], out mqNum);
            if (threadNum <= 0)
            {
                Console.WriteLine("线程数必须大于0");
                publishMsg(threadNum, mqNum);
            }
            if (mqNum <= 0)
            {
                Console.WriteLine("队列数数必须大于0");
                publishMsg(threadNum, mqNum);
            }
            publish(threadNum, mqNum);
            publishMsg(threadNum, mqNum);
        }

        /// <summary>
        /// 发布消息
        /// </summary>
        /// <param name="MsgNum">每个线程消息数</param>
        /// <param name="ThreadNum">总线程数</param>
        static void publish(int ThreadNum, int MsgNum)
        {
            for(int t=0;t< ThreadNum;t++)
            {
                List<string> msgs = new List<string>();
                for (int i = 0; i < MsgNum; i++)
                {
                    msgs.Add("aaa" + i.ToString());
                }
                Task.Run(() =>
                {
                    foreach (var itm in msgs)
                    {
                        bus.PubSub.PublishAsync(new BusMessage { JsonData = itm }, "order.created");
                      
                    }
                });
            }
           
        }
    }
}
